<template>
  <div>
    <!-- 固定在顶部，所以写一个fixed -->
    <van-nav-bar fixed>
      <template #left>
        <img :src="imgObj" alt="" class="logo">
      </template>
      <template #right>
        <van-icon name="search" size="0.48rem" color="#fff" @click="$router.push('/search')"></van-icon>
      </template>
    </van-nav-bar>
    <!-- 频道部分 -->
    <van-tabs v-model="channelId" animated sticky offset-top="1.226667rem">
      <van-tab v-for="item in channelList" :key="item.id" :title="item.name" :name="item.id">
        <!-- {{ item.name }} -->
        <article-list :cid="channelId"></article-list>
      </van-tab>

    </van-tabs>
    <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="show = true"/>
    <!-- 弹出层组件 -->
    <van-popup v-model="show" class="edit_wrap" @closed="onPopupClosed">
      <!-- 弹出层的主体区域 -->
      <channel-edit :userChannelList="channelList" @close="show = false" @addChannel="addChannelFn" @removeChannel="removeChannelFn" ref="channelEdit"
      @changeChannel="channgeChannelFn"
      ></channel-edit>
    </van-popup>
  </div>
</template>

<script>
import logoPng from '../../assets/toutiao_logo.png'
import { userChannelAPI, updateChannelAPI } from '@/api'
import ArticleList from '@/views/Home/ArticleList'
import ChannelEdit from './ChannelEdit.vue'

export default {
  name: 'Home',
  data () {
    return {
      imgObj: logoPng,
      active: 0,
      channelList: [],
      channelId: 0,
      show: false
    }
  },
  components: {
    ArticleList,
    ChannelEdit
  },
  methods: {
    async addChannelFn (val) {
      this.channelList.push(val)
    },
    async updateChannel () {
      const list = this.channelList.filter(item => {
        return item.id !== 0
      })
      const resArr = list.map((item, index) => {
        const newObj = { ...item }
        newObj.seq = index + 1
        delete newObj.name
        return newObj
      })
      console.log(resArr)
      await updateChannelAPI({
        channels: resArr
      })
    },
    async removeChannelFn (obj) {
      const index = this.channelList.findIndex(item => item.id === obj.id)
      this.channelList.splice(index, 1)
      this.updateChannel()
    },
    onPopupClosed () {
      this.$refs.channelEdit.isEdit = false
    },
    // 切换频道
    channgeChannelFn (obj) {
      this.channelId = obj.id // 传过来的频道ID, 影响tabs默认v-model的选择
    }
  },
  async created () {
    const res = await userChannelAPI()
    this.channelList = res.data.data.channels
  }
}
</script>

<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
    padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
